package com.rainsoftware.LicenseSystem.controllers.api;

import com.rainsoftware.LicenseSystem.services.ProductService;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping
    public ResponseEntity<String> onPost(@RequestParam(required = false) String name,
                                         @RequestBody(required = false) String jsonBody) {
        if (jsonBody != null) {
            JSONObject json = new JSONObject(jsonBody);
            name = json.optString("name");
        }
        StandardResponse response = productService.createProduct(name);
        return response.build();
    }

    @GetMapping
    public ResponseEntity<String> onGet(
            @RequestParam(required = false) Integer limit,
            @RequestBody(required = false) String jsonBody
    ) {
        if (limit == null)
            limit = -1;
        if (jsonBody != null) {
            JSONObject json = new JSONObject(jsonBody);
            limit = json.optInt("limit", -1);
        }
        StandardResponse response = productService.getProductList(limit);
        return response.build();
    }

    @PostMapping("/delete")
    public ResponseEntity<String> deleteProduct(@RequestBody Map<String, Object> requestBody) {
        List<Integer> productsArray = (List<Integer>) requestBody.get("products");
        StandardResponse response = productService.deleteMultipleProducts(productsArray);
        return response.build();
    }
}
